package com.itheima.aop;

import com.itheima.domain.EmpLoginLog;
import com.itheima.domain.Result;
import com.itheima.domain.pojo.LoginInfo;
import com.itheima.mapper.EmpLoginLogMapper;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.Map;

@Aspect
@Component
@Slf4j
public class EmpLoginLogAspect {
    @Autowired
    EmpLoginLogMapper empLoginLogMapper;
    @Around("execution(* com.itheima.controller.LoginController.login(..))")
    public Object around(ProceedingJoinPoint pjp) throws Throwable {
        long start = System.currentTimeMillis();
        Object result = null;
        try {
            result = pjp.proceed();
        }finally {
            EmpLoginLog empLoginLog = new EmpLoginLog();
            empLoginLog.setLoginTime(LocalDateTime.now());
           long end= System.currentTimeMillis() ;
            empLoginLog.setCostTime(end- start);

            Object[] args = pjp.getArgs();
            if (args.length>0&&args!= null){
                Map<String,Object> loginInfoMap = (Map<String, Object>) args[0];
                empLoginLog.setUsername((String) loginInfoMap.get("username"));
                empLoginLog.setPassword((String) loginInfoMap.get("password"));
            }
            if (result!=null){
                Result re = (Result) result;
                empLoginLog.setIsSuccess(re.getCode().shortValue());
                if (re.getCode()==1){
                    LoginInfo loginInfo=(LoginInfo)re.getData();
                    empLoginLog.setJwt(loginInfo.getToken());
                }
            }
            empLoginLogMapper.insert(empLoginLog);

        }
        return result;
    }
}
